let express = require("express");
let path = require("path"); //系统路径模块
const connect = require("../config/config.js");
const router = express.Router();
let Long = require('mongodb').Long;
const log4js  = require("../config/log.js");
let logger=log4js.getLogger("info")
//获取客户端ip地址
var ip=require("../public/getIp.js");

//服务器
//增加服务器
router.post("/addServer", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	if (req.body.newIcon === "1" || req.body.newIcon === "有图标") {
		req.body.newIcon = true;
	} else {
		req.body.newIcon = false;
	}
	let serverobj = {
		serverId: req.body.serverId,
		serverName: req.body.serverName,
		serverIp: req.body.serverIp,
		loginPort: req.body.loginPort,
		gateIp: req.body.gateIp,
		gatePort: req.body.gatePort,
		newIcon: req.body.newIcon,
		enabled: false,
		gmUrl: req.body.gmUrl,
		openTime: Long.fromNumber(req.body.openTime)
	};
	connect(function(err, db) {
		if (err){
			logger.info("数据库连接失败");
		} else {
			db.collection("config_server").createIndex({
				"serverId": 1
			},{
				"unique": true
			});
			db.collection("config_server").find({
				serverId: serverobj.serverId
			}, function(err, data) {
				data.toArray(function(err, item) {
					if (item.length < 1) {
						db.collection("config_server").insertOne(serverobj, (err, result) => {
							res.send({
								code: 200,
								msg: "添加服务器数据成功",
								result: result
							})
						});
					} else {
						res.send({
							code: 400,
							msg: "服务器id不能重复"
						})
					}
				});
			})
		}
	});
});
//获取服务器列表
router.get("/getServer", (req, res) => {
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
			return;
		} else {
			db.collection("config_server").aggregate([{
				$project: {
					_id: 0,
					"serverId": 1,
					"serverName": 1,
					"enabled": 1,
					"serverIp": 1,
					"loginPort": 1,
					"newIcon": 1,
					"gmUrl": 1,
					"openTime":1,
					"gateIp":1,
					"gatePort":1
				}
			}]).toArray((err, data) => {
				let serverArr = [];
				data.forEach((item) => {
					//判断后台传过来的对象是否为空
					if(Object.keys(item).length === 0) {
						return;
					} else {
						if(item.newIcon === true) {
							item.newIcon = "有图标"
						} else {
							item.newIcon = "没有图标"
						}
						let obj = {
							serverId: parseInt(item.serverId),
							serverName: item.serverName,
							enabled: item.enabled,
							serverIp: item.serverIp,
							loginPort: item.loginPort,
							newIcon: item.newIcon,
							gmUrl: item.gmUrl,
							openTime:item.openTime,
							gateIp:item.gateIp,
							gatePort:item.gatePort
						};
						serverArr.push(obj);
						serverArr.sort((a, b) => {
							return a.serverId - b.serverId;
						});
					}
				});
				res.send({
					code: 200,
					msg: "请求成功",
					result: serverArr
				})
			})
		}
	})
});
//编辑服务器
router.post("/updServer/:id", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	if (req.body.newIcon === "有图标" || req.body.newIcon === "1") {
		req.body.newIcon = true;
	} else {
		req.body.newIcon = false;
	}
	let serverobj = {
		serverId: req.body.serverId,
		serverName: req.body.serverName,
		serverIp: req.body.serverIp,
		loginPort: req.body.loginPort,
		newIcon: req.body.newIcon,
		gateIp: req.body.gateIp,
		gatePort: req.body.gatePort,
		gmUrl: req.body.gmUrl,
		openTime:Long.fromNumber(req.body.openTime)
	};
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			if(req.body.serverId==req.params.id){
				db.collection("config_server").updateMany({
					serverId: parseInt(req.params.id)
				}, {
					$set: serverobj
				}, {
					'upsert': true,
					multi: true
				}).then(result => {
					res.send({
						code: 200,
						msg: "服务器编辑成功！",
						result: result
					})
				})
			}else{
				db.collection("config_server").find({
					serverId: serverobj.serverId
				}, function(err, data) {
					data.toArray(function(err, item) {
						if (item.length < 1) {
							db.collection("config_server").updateMany({
								serverId: parseInt(req.params.id)
							},{
								$set: serverobj
							},{
								'upsert': true,
								multi: true
							}).then(result => {
								res.send({
									code: 200,
									msg: "服务器编辑成功！",
									result: result
								})
							})
						} else {
							res.send({
								code: 400,
								msg: "服务器id不能重复"
							})
						}
					});
				})
			}
		}
	})
});
//启用服务器
router.post("/enableServer", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	const serverId = req.body.serverId;
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_server").updateMany({
				serverId: serverId
			},{
				$set:{
					enabled: true
				}
			},{
				'upsert': true,
				multi: true
			}).then(result => {
				res.send({
					code: 200,
					msg: "服务器启用成功！",
					result: result
				})
			})
		}
	})
});
//禁用服务器
router.post("/disableServer", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	const serverId = req.body.serverId;
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_server").updateMany({
				serverId: serverId
			},{
				$set: {
				  enabled: false
				}
			},{
				'upsert': true,
				multi: true
			}).then(result => {
				res.send({
					code: 200,
					msg: "服务器禁用成功！",
					result: result
				})
			})
		}
	})
});

//服务器组
//增加服务器组
router.post("/addServerGroup", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	let servergroupobj = {
		serverGroupId: req.body.serverGroupId,
		serverGroupName: req.body.serverGroupName,
		serverIds: req.body.serverIds,
		enabled: false
	};
	connect(function(err, db){
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_server_group").find({
				serverGroupId: servergroupobj.serverGroupId
			}, function(err, data) {
				data.toArray(function(err, item) {
					if (item.length < 1) {
						db.collection("config_server_group").insertOne(servergroupobj, (err, result) => {
							res.send({
								code: 200,
								msg: "添加服务器组数据成功",
								result: result
							})
						});
					}else{
						res.send({
							code: 400,
							msg: "服务器组id和端口号不能重复"
						})
					}
				});
			})
		}
	});
});
//获取服务器组列表
router.get("/getServerGroup", (req, res) => {
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
			return;
		} else {
			db.collection("config_server_group").aggregate([{
				$project: {
					_id: 0,
					"serverGroupId": 1,
					"serverGroupName": 1,
					"enabled": 1,
					"serverIds": 1,
				}
			}]).toArray((err, data) => {
				let servergroupArr = [];
				data.forEach((item) => {
					//判断后台传过来的对象是否为空
					if (Object.keys(item).length === 0){
						return;
					}else{
						let obj = {
							serverGroupId: parseInt(item.serverGroupId),
							serverGroupName: item.serverGroupName,
							enabled: item.enabled,
							serverIds: item.serverIds,
						};
						servergroupArr.push(obj);
						servergroupArr.sort((a, b) => {
							return a.serverGroupId - b.serverGroupId;
						});
					}
				});
				res.send({
					code: 200,
					msg: "请求成功",
					result: servergroupArr
				})
			})
		}
	})
});
//编辑服务器组
router.post("/updServerGroup/:id", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	let serverobj = {
		serverGroupId: req.body.serverGroupId,
		serverGroupName: req.body.serverGroupName,
		serverIds: req.body.serverIds,
	};
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			if(req.body.serverGroupId==req.params.id){
				db.collection("config_server_group").updateMany({
					serverGroupId: parseInt(req.params.id)
				},{
					$set: serverobj
				},{
					'upsert': true,
					multi: true
				}).then(result => {
					res.send({
						code: 200,
						msg: "服务器组编辑成功！",
						result: result
					})
				})
			}else{
				db.collection("config_server_group").find({
					serverGroupId: serverobj.serverGroupId
				}, function(err, data) {
					data.toArray(function(err, item) {
						if (item.length < 1) {
							db.collection("config_server_group").updateMany({
								serverGroupId: parseInt(req.params.id)
							},{
								$set: serverobj
							},{
								'upsert': true,
								multi: true
							}).then(result => {
								res.send({
									code: 200,
									msg: "服务器组编辑成功！",
									result: result
								})
							})
						}else{
							res.send({
								code: 400,
								msg: "服务器id不能重复"
							})
						}
					});
				})
			}
		}
	})
});
//启用服务器组
router.post("/enableServerGroup", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	const serverGroupId = req.body.serverGroupId;
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_server_group").updateMany({
				serverGroupId: parseInt(serverGroupId)
			},{
				$set: {
					enabled: true
				}
			},{
				'upsert': true,
				multi: true
			}).then(result => {
				res.send({
					code: 200,
					msg: "服务器组启用成功！",
					result: result
				})
			})
		}
	})
});
//禁用服务器组
router.post("/disableServerGroup", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	const serverGroupId = req.body.serverGroupId;
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_server_group").updateMany({
				serverGroupId: parseInt(serverGroupId)
			},{
				$set: {
					enabled: false
				}
			},{
				'upsert': true,
				multi: true
			}).then(result => {
				res.send({
					code: 200,
					msg: "服务器组禁用成功！",
					result: result
				})
			})
		}
	})
});

//邮件
//增加邮件
router.post("/addmail", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	if (req.body.userMinLevel === "") {
		req.body.userMinLevel = null;
	}
	if (req.body.userMinAfk === "") {
		req.body.userMinAfk = null;
	}
	let mailobj = {
		mailId: 100,
		mailType: 1,
		awards: req.body.awards,
		specifiedServerIds: req.body.specifiedServerIds,
		effectStartTime: Long.fromNumber(req.body.effectStartTime),
		effectEndTime: Long.fromNumber(req.body.effectEndTime),
		userRegStartTime: Long.fromNumber(req.body.userRegStartTime),
		userRegEndTime: Long.fromNumber(req.body.userRegEndTime),
		specifiedUids: req.body.specifiedUids,
		titles: req.body.title,
		bodies: req.body.content,
		describe: req.body.describe,
		enabled: false,
		userMinLevel: req.body.userMinLevel,
		userMinAfk: req.body.userMinAfk
	};
	connect(function(err, db) {
		if (err) {
			logger.info(err);
		} else {
			db.collection("config_mail").findOneAndUpdate({
				increase: 1
			}, {
				$inc: {
					mailIds: 1
				}
			}, {
				"upsert": true,
				"returnOriginal": false
			}, (err, data) => {
				if (err) {
					logger.info(err);
					return;
				} else {
					mailobj.mailId = mailobj.mailId + data.value.mailIds;
					db.collection("config_mail").insertOne(mailobj, (err, result) => {
						res.send({
							code: 200,
							msg: "添加邮件数据成功",
							result: result
						})
					});
				}
			})
		}
	});
});
//获取邮件信息
router.get("/getmail", (req, res) => {
	connect(function(err, db) {
		if (err) {
			logger.info(err);
			return;
		} else {
			db.collection("config_mail").aggregate([{
				$project: {
					_id: 0,
					"mailId": 1,
					"describe": 1,
					"enabled": 1,
					"sendingTime": 1,
					"effectStartTime": 1,
					"effectEndTime": 1,
				}
			}]).toArray((err, data) => {
				let mailArr = [];
				data.forEach((item) => {
					//判断后台传过来的对象是否为空
					if(Object.keys(item).length === 0){
						return;
					}else{
						let obj = {
							mailId: parseInt(item.mailId),
							describe: item.describe,
							enabled: item.enabled,
							sendingTime: item.sendingTime,
							effectEndTime: item.effectEndTime,
							effectStartTime: item.effectStartTime,
						};
						mailArr.push(obj);
						mailArr.sort((a, b) => {
							return b.mailId - a.mailId;
						});
					}
				});
				res.send({
					code: 200,
					msg: "请求成功",
					result: mailArr
				})
			})
		}
	})
});
//按mail_id获取邮件信息
router.post("/getmailId", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	let mailId = req.body.mailId;
	connect(function(err, db) {
		if (err) {
			logger.info(err);
			return;
		} else {
			db.collection("config_mail").find({
				mailId: mailId
			}).toArray((err, data) => {
				if (err) {
					return;
				}else{
					res.send({
						code: 200,
						msg: "获取成功",
						result: data
					})
				}
			})
		}
	})
});
//编辑邮件
router.post("/updmail/:mailId", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	if (req.body.userMinLevel ==="") {
		req.body.userMinLevel = null;
	}
	if (req.body.userMinAfk === "") {
		req.body.userMinAfk = null;
	}
	let mailobj = {
		mailType: 1,
		awards: req.body.awards,
		specifiedServerIds: req.body.specifiedServerIds,
		effectStartTime: Long.fromNumber(req.body.effectStartTime),
		effectEndTime: Long.fromNumber(req.body.effectEndTime),
		userRegStartTime: Long.fromNumber(req.body.userRegStartTime),
		userRegEndTime: Long.fromNumber(req.body.userRegEndTime),
		specifiedUids: req.body.specifiedUids,
		titles: req.body.title,
		bodies: req.body.content,
		describe: req.body.describe,
		userMinLevel:req.body.userMinLevel,
		userMinAfk:req.body.userMinAfk
	};
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_mail").updateMany({
				mailId: parseInt(req.params.mailId)
			},{
				$set: mailobj
			},{
				'upsert': true,
				multi: true
			}).then(result => {
				res.send({
					code: 200,
					msg: "邮件编辑成功！",
					result: result
				})
			})
		}
	})
});
//启用邮件
router.post("/enableMail", (req, res) => {
	const mailId = parseInt(req.body.mailId);
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_mail").find({
				mailId: mailId
			}).toArray((err, data) => {
				if (err) {
					return;
				} else {
					// 获取启用后的日志信息
					data.forEach(item=>{
						var params = {
						  date:req.body.date,
						  bodies: item.bodies,
					      awards: item.awards,
						  mailId: item.mailId,
						  uid: item.specifiedUids,
						  ip4:ip.getClientIp(req),
						  user_actions:req.body.user_actions
						}
						logger.info(params);
					})
					db.collection("config_mail").updateMany({
						mailId: mailId
					},{
						$set: {
							enabled: true
						}
					},{
						'upsert': true,
						multi: true
					}).then(result => {
						res.send({
							code: 200,
							msg: "邮件启用成功！",
							result: result
						})
					})
				}				
			})
		}
	})
});
//禁用邮件
router.post("/disableMail", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	const mailId = parseInt(req.body.mailId);
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_mail").updateMany({
				mailId: mailId
			},{
				$set: {
					enabled: false
				}
			},{
				'upsert': true,
				multi: true
			}).then(result => {
				res.send({
					code: 200,
					msg: "邮件禁用成功！",
					result: result
				})
			})
		}
	})
});

//兑换码
//增加兑换码
router.post("/addCode", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	let codeobj = {
		awards: req.body.awards,
		code: req.body.code,
		startTime: Long.fromNumber(req.body.startTime),
		endTime: Long.fromNumber(req.body.endTime),
		userLimit: parseInt(req.body.userLimit),
		describe: req.body.describe,
		enabled: false,
	};
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_exchange_code").find({
				code: codeobj.code
			}, function(err, data) {
				data.toArray(function(err, item) {
					if (item.length < 1) {
						db.collection("config_exchange_code").insertOne(codeobj, (err, result) => {
							res.send({
								code: 200,
								msg: "添加服务器数据成功",
								result: result
							})
						});
					} else {
						res.send({
							code: 400,
							msg: "兑换码不能重复"
						})
					}
				});
			})
		}
	});
});
//获取兑换码信息
router.get("/getCode", (req, res) => {
	connect(function(err, db) {
		if (err) {
			logger.info(err);
			return;
		} else {
			db.collection("config_exchange_code").aggregate([{
				$project: {
					_id: 0,
					"code": 1,
					"describe": 1,
					"enabled": 1,
					"startTime": 1,
					"endTime": 1,
					"userLimit": 1,
				}
			}]).toArray((err, data) => {
				let CodeArr = [];
				data.forEach((item) => {
					//判断后台传过来的对象是否为空
					if (Object.keys(item).length === 0) {
						return;
					} else {
						let obj = {
							code: item.code,
							describe: item.describe,
							startTime: item.startTime,
							endTime: item.endTime,
							userLimit: item.userLimit,
							enabled:item.enabled
						};
						CodeArr.push(obj);
					}
				});
				res.send({
					code: 200,
					msg: "请求成功",
					result: CodeArr
				})
			})
		}
	})
});
//按兑换码获取兑换码信息
router.post("/getCodeId", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	let code = req.body.code;
	connect(function(err, db) {
		if (err) {
			logger.info(err);
			return;
		} else {
			db.collection("config_exchange_code").find({
				code: code
			}).toArray((err, data) => {
				if (err) {
					return;
				} else {
					res.send({
						code: 200,
						msg: "获取成功",
						result: data
					})
				}
			})
		}
	})
});
//编辑兑换码
router.post("/updCode/:code", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	let codeobj = {
		awards: req.body.awards,
		code: req.body.code,
		startTime: Long.fromNumber(req.body.startTime),
		endTime: Long.fromNumber(req.body.endTime),
		userLimit: parseInt(req.body.userLimit),
		describe: req.body.describe
	};
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_exchange_code").updateMany({
				code: req.params.code
			}, {
				$set: codeobj
			}, {
				'upsert': true,
				multi: true
			}).then(result => {
				res.send({
					code: 200,
					msg: "兑换码编辑成功！",
					result: result
				})
			})
		}
	})
});
//启用兑换码
router.post("/enableCode", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	const code = req.body.code;
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_exchange_code").updateMany({
				code: code
			}, {
				$set: {
					enabled: true
				}
			}, {
				'upsert': true,
				multi: true
			}).then(result => {
				res.send({
					code: 200,
					msg: "兑换码启用成功！",
					result: result
				})
			})
		}
	})
});
//禁用兑换码
router.post("/disableCode", (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	const code = req.body.code;
	connect(function(err, db) {
		if (err) {
			logger.info("数据库连接失败");
		} else {
			db.collection("config_exchange_code").updateMany({
				code: code
			}, {
				$set: {
					enabled: false
				}
			}, {
				'upsert': true,
				multi: true
			}).then(result => {
				res.send({
					code: 200,
					msg: "兑换码禁用成功！",
					result: result
				})
			})
		}
	})
});

module.exports = router;
